package com.hyg.lib_common.loginpart;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSONObject;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.DataModel.EventBusMessage;
import com.hyg.lib_common.DataModel.ReceiveData;
import com.hyg.lib_common.DataModel.YangShengInfo.ReceiveDataInt;
import com.hyg.lib_common.DataModel.personal.LoginReceiveUserInfo;
import com.hyg.lib_common.Net.CommonHttpUtil;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.lib_common.R;
import com.hyg.lib_common.WebView.WebViewActivity;
import com.hyg.lib_common.databinding.ActivityVerificationLoginBinding;
import com.hyg.lib_common.sweetalertdialog.SweetAlertDialog;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Response;

public class VerificationLoginActivity extends BaseActivity {

    ActivityVerificationLoginBinding binding;
    String phone = "";
    String type = "login";
    String openid = "";
    Handler handler;
    int number = 59;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityVerificationLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        init();
    }

    public void init() {
        phone = getIntent().getStringExtra("phone");
        type = getIntent().getStringExtra("type");
        openid = getIntent().getStringExtra("openid");
        Log.i("lgb", "init: " + phone);
        initView();
        initTimer();
    }

    /**
     * description: 读秒倒计时
     *
     * @author visitant
     * @time 2021/4/2 16:22
     */
    @SuppressLint("HandlerLeak")
    public void initTimer() {
        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    number--;
                    if (number <= 0) {
                        handler.removeCallbacksAndMessages(null);
                        number = 59;
                        binding.tvSecondHint.setText("重新发送");
                        binding.tvSecondHint.setClickable(true);
                    } else {
                        handler.sendEmptyMessageDelayed(1, 1000);
                        binding.tvSecondHint.setText(number + "s后重发");
                    }
                }
            }
        };
        handler.sendEmptyMessageDelayed(1, 1000);
    }


    public void initView() {
        StatusBarUtil.setStatusBar(1, this, getResources().getColor(R.color.white), 00, null, null, true);
        binding.tvCodeNumber.setText(gerFormatPhone(phone));
        binding.tvSecondHint.setClickable(false);
        binding.tvSecondHint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonHttpUtil.getCode(phone, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ErrorDialog("连接服务器失败，请稍后重试！");
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        Log.i("lgb", "onResponse: "+result);
                        ReceiveData receiveData = JSONObject.parseObject(result, ReceiveData.class);
                        if (receiveData.getCode().equals("200")) {
                            handler.sendEmptyMessageDelayed(1, 1000);
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ErrorDialog(receiveData.getMessage());
                                }
                            });
                        }
                    }
                });
            }
        });
        binding.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.tvAgreement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(VerificationLoginActivity.this, WebViewActivity.class);
                it.putExtra("url", UrlUtils.PrivacyUrl);
                it.putExtra("title", "隐私政策与免责声明");
                it.putExtra("type", "Privacy");
                startActivity(it);
            }
        });

        binding.etNumber1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(binding.etNumber1.getText().toString())) {
                    binding.etNumber2.requestFocus();
                }
            }
        });
        binding.etNumber1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    binding.etNumber1.setText("");
                }
            }
        });


        binding.etNumber2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(binding.etNumber2.getText().toString())) {
                    binding.etNumber3.requestFocus();
                }
            }
        });
        binding.etNumber2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    binding.etNumber2.setText("");
                }
            }
        });
        binding.etNumber2.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode==67 && event.getAction()==KeyEvent.ACTION_DOWN && TextUtils.isEmpty(binding.etNumber2.getText())){
                    binding.etNumber1.requestFocus();
                }
                return false;
            }
        });


        binding.etNumber3.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(binding.etNumber3.getText().toString())) {
                    binding.etNumber4.requestFocus();
                }
            }
        });
        binding.etNumber3.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode==67 && event.getAction()==KeyEvent.ACTION_DOWN && TextUtils.isEmpty(binding.etNumber3.getText())){
                    binding.etNumber2.requestFocus();
                }
                return false;
            }
        });
        binding.etNumber3.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    binding.etNumber3.setText("");
                }
            }
        });

        binding.etNumber4.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    binding.etNumber4.setText("");
                }
            }
        });

        binding.etNumber4.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode==67 && event.getAction()==KeyEvent.ACTION_DOWN && TextUtils.isEmpty(binding.etNumber4.getText())){
                    binding.etNumber3.requestFocus();
                }
                return false;
            }
        });

        binding.etNumber4.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(binding.etNumber4.getText().toString())) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    if(type.equalsIgnoreCase("login")){
                        login(phone, binding.etNumber1.getText().toString() + binding.etNumber2.getText().toString() + binding.etNumber3.getText().toString() + binding.etNumber4.getText().toString());
                    }else{
                        Log.i("lgb", "afterTextChanged: type="+type);
                            bindPhone(phone,openid,binding.etNumber1.getText().toString() + binding.etNumber2.getText().toString() + binding.etNumber3.getText().toString() + binding.etNumber4.getText().toString());
                    }
                }
                Log.i("lgb", "afterTextChanged: " + s);
            }
        });
        binding.etNumber1.requestFocus();
        InputMethodManager inputManager = (InputMethodManager) binding.etNumber1.
                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(binding.etNumber1, InputMethodManager.SHOW_FORCED);
    }

    /**
     * description: 转化手机显示格式  137 xxxx  xxxx
     *
     * @author visitant
     * @time 2021/4/2 16:22
     */
    public String gerFormatPhone(String phone) {
        if (TextUtils.isEmpty(phone) || phone.length() != 11) {
            return phone;
        } else {
            return phone.substring(0, 3) + " " + phone.substring(3, 7) + " " + phone.substring(7);
        }
    }

    /**
     * description:登录
     *
     * @author visitant
     * @time 2021/4/2 16:21
     */
    public void login(String phone, String code) {

        CommonHttpUtil.loginByCode(phone, code, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ErrorDialog("连接服务器失败,请重试!");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("lgb", "onResponse:bindphone "+result);
                ReceiveDataInt data = JSONObject.parseObject(result, ReceiveDataInt.class);
                if (data.getCode() == 200) {
                    LoginReceiveUserInfo userInfo = JSONObject.parseObject(data.getData(), LoginReceiveUserInfo.class);
                    editorn = sn.edit();
                    editorn.putString("phone", userInfo.getUserInfo().getPhone());
                    editorn.putString("token", userInfo.getToken());
                    editorn.apply();
                    ToIntent(Constants.PATH_ACTIVITY_MAIN, true);
                    EventBus.getDefault().post(new EventBusMessage("startMainActivity"));
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ErrorDialog(data.getMessage());
                        }
                    });
                }
            }
        });
    }


    public void bindPhone(String phone,String openid,String code){
        Log.i("lgb", "bindPhone:phone = "+phone);
        Log.i("lgb", "bindPhone: openid= "+openid);
        Log.i("lgb", "bindPhone: code= "+code);

        CommonHttpUtil.bindPhone(phone, openid,code, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ErrorDialog("连接服务器失败,请重试!");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("lgb", "onResponse result111: "+result);
                ReceiveDataInt data = JSONObject.parseObject(result, ReceiveDataInt.class);
                if (data.getCode() == 200) {
                    LoginReceiveUserInfo userInfo = JSONObject.parseObject(data.getData(), LoginReceiveUserInfo.class);
                    editorn = sn.edit();
                    editorn.putString("phone", userInfo.getUserInfo().getPhone());
                    editorn.putString("token", userInfo.getToken());
                    editorn.apply();

                    Log.i("lgb", "onResponse:phone= "+userInfo.getUserInfo().getPhone());
                    Log.i("lgb", "token= "+userInfo.getToken());

                    ToIntent(Constants.PATH_ACTIVITY_MAIN, true);
                    EventBus.getDefault().post(new EventBusMessage("startMainActivity"));
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ErrorDialog(data.getMessage());
                        }
                    });
                }
            }
        });














    }

















    @Override
    public void finish() {
        super.finish();
        handler.removeCallbacksAndMessages(null);
    }
}